import functools

import random
import time
import datetime

from flask import (
	Blueprint, flash, g, redirect, render_template, request, session, url_for, jsonify, current_app
)

from werkzeug.security import check_password_hash, generate_password_hash

from garden import db
from garden.models import User, Community


bp = Blueprint('auth', __name__, url_prefix='/auth')


@bp.route('/register', methods=('GET', 'POST'))
def register():
	if request.method == 'POST':
		username = request.form['username']
		password = request.form['password']
		db = get_db()
		error = None

		if not username:
			error = 'Username is required.'
		elif not password:
			error = 'Password is required.'
		elif db.execute(
			'SELECT id FROM user WHERE username = ?', (username,)
		).fetchone() is not None:
			error = 'User {} is already registered.'.format(username)

		if error is None:
			db.execute(
				'INSERT INTO user (username, password) VALUES (?, ?)',
				(username, generate_password_hash(password))
			)
			db.commit()
			
			return redirect(url_for('auth.login'))

		flash(error)
	return render_template('auth/register.html')

@bp.route('/login', methods=('GET', 'POST'))
def login():
	print('User-Agent %s' % request.headers.get('User-Agent'))
	print('User-Agent platform %s' % request.user_agent.platform) #客户端操作系统
	print('User-Agent browser %s' % request.user_agent.browser) #客户端的浏览器
	print('User-Agent version %s' % request.user_agent.version) #客户端浏览器的版本
	print('User-Agent language %s' % request.user_agent.language) #客户端浏览器的语言
	print('User-Agent string %s' % request.user_agent.string) #字符串，包含以上4种信息，等同于request.headers.get('User-Agent')

	if 'micromessenger' in request.user_agent.string.lower():
		print("micro messenger browser")

	if request.method == 'POST':
		tel = request.form['tel']
		dnmcCode = request.form['dnmcCode']
		now = int(time.time())

		if 'tel' not in session or 'dnmcCode' not in session or 'codeTime' not in session:
			return jsonify({"success":False,"errorMessage":"请重新获取动态码"})

		stel = session['tel']
		sdnmcCode = session['dnmcCode']
		scodeTime = session['codeTime']

		print('tel is %s ,stel is %s ;dnmcCode is %s ,sdnmcCode is %s ' % (tel,stel,dnmcCode,sdnmcCode))
		# print (tel == stel)
		# print (dnmcCode == sdnmcCode)
		# print(tel != stel or dnmcCode != sdnmcCode)

		if tel != stel or dnmcCode != sdnmcCode:
			return jsonify({"success":False,"errorMessage":"动态码验证失败"})
		else:
			if (now - scodeTime) > 300:
				return jsonify({"success":False,"errorMessage":"动态码超时"})

		user = User.query.filter_by(mobile=tel).first()
		print(user)
		if user is None:
			u = User(nickname=tel, loginname=tel, passwd=None, email=None, mobile=tel, idno=None, realname=None, is_valid=None, roles=None, \
				create_time=datetime.datetime.now(), modify_time=None, status=1, openid=None, avatar=None, cmnt_id=None)
			db.session.add(u)
			db.session.commit()
			user = u
		session.clear()
		session['user_id'] = user.id
		return jsonify({"success":True,"errorMessage":"","redirect2":url_for('index')})
	return render_template('auth/login.html')

@bp.before_app_request
def load_logged_in_user():
	user_id = session.get('user_id')

	if user_id is None:
		g.user = None
	else:
		g.user = User.query.get(user_id)

@bp.route('/logout')
def logout():
	session.clear()
	return redirect(url_for('index'))

def login_required(view):
	@functools.wraps(view)
	def wrapped_view(**kwargs):
		if g.user is None:
			return redirect(url_for('auth.login'))

		return view(**kwargs)

	return wrapped_view

@bp.route('/sendDnmcCode', methods=['POST'])
def send_dnmc_code():
	now = int(time.time())
	# print(now)
	codeTime = session.get('codeTime')
	if codeTime is not None :
		if (now - codeTime) < 60:
			return jsonify({"success":False,"errorMessage":"获取动态码太频繁，轻稍后再获取"})

	tel = request.form['tel']
	code = random.randint(1000, 9999)
	session['tel'] = tel
	session['dnmcCode'] = str(code)
	session['codeTime'] = now

	current_app.logger.info("tel is %s dynamic code is %s ",tel,code)

	return jsonify({"success":True,"errorMessage":""})

@bp.route('/profile')
@login_required
def profile():
	return render_template('auth/profile.html')


@bp.route('/selectCommunity', methods=('GET', 'POST'))
@login_required
def select_community():
	if request.method == 'POST':
		if 'cmnt_id' in request.form :
			cmnt_id = request.form['cmnt_id']
			user = g.user 
			user.cmnt_id = cmnt_id
			db.session.add(user)
			db.session.commit()
			return jsonify({"success":True,"errorMessage":""})
		else:
			return jsonify({"success":False,"errorMessage":"miss cmnt_id"})
	else :
		communities = Community.query.filter_by(is_visible = True)
		print(communities)
		return render_template('auth/community.html',communities=communities)